package site.lanmushan.quiz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import site.lanmushan.common.exception.OperateException;
import site.lanmushan.common.mapper.wrapper.DefaultWrapper;
import site.lanmushan.common.mapper.wrapper.QueryWrapper;
import site.lanmushan.common.query.service.BaseService;
import site.lanmushan.quiz.api.entity.QuizTbQuestion;
import site.lanmushan.quiz.api.entity.QuizTbQuestionAnswer;
import site.lanmushan.quiz.api.service.IQuizTbQuestionService;
import site.lanmushan.quiz.api.service.IQuizTbQuestionAnswerService;
import site.lanmushan.quiz.api.vo.QuestionAnswersVo;
import site.lanmushan.quiz.api.vo.QuizTbQuestionListVo;
import site.lanmushan.quiz.mapper.QuizTbQuestionMapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author dy
 */

@Service
@Transactional(rollbackFor = Exception.class)
public class QuizTbQuestionServiceImpl extends BaseService<QuizTbQuestion, QuizTbQuestionMapper> implements IQuizTbQuestionService {
    @Autowired
    IQuizTbQuestionAnswerService iQuizTbQuestionAnswerService;

    @Override
    public Integer selectCountByBankCode(String bankCode) {
        QuizTbQuestion quizTbQuestion = new QuizTbQuestion();
        quizTbQuestion.setFkQuestionBankCode(bankCode);
        return getQueryMapper().selectCount(quizTbQuestion);
    }

    @Override
    public List<QuizTbQuestionListVo> selectBankInfoByBankCode(String bankCode) {
        QuizTbQuestion query = new QuizTbQuestion();
        query.setFkQuestionBankCode(bankCode);
        List<QuizTbQuestion> quizTbQuestionList = getQueryMapper().select(query);
        if (quizTbQuestionList.size() == 0) {
            throw new OperateException("该题库没有题目");
        }
        return BeanUtil.copyToList(quizTbQuestionList, QuizTbQuestionListVo.class);
    }

    @Override
    public QuestionAnswersVo selectQuestionAndOptionsById(Long id) {
        QuizTbQuestion quizTbQuestion = getQueryMapper().selectByPrimaryKey(id);
        QueryWrapper queryWrapper = new DefaultWrapper();
        queryWrapper.in("fk_question_id", id);
        List<QuizTbQuestionAnswer> list = iQuizTbQuestionAnswerService.selectQueryWrapper(queryWrapper);
        List<QuizTbQuestionAnswer> quizTbQuestionAnswers = list.stream().map(ite -> {
            ite.setScoreValue(null);
            ite.setAnswerCorrect(null);
            ite.setAnswerGroup(null);
            ite.setWeight(null);
            return ite;
        }).collect(Collectors.toList());
        QuestionAnswersVo questionAnswersVo = BeanUtil.copyProperties(quizTbQuestion, QuestionAnswersVo.class);
        questionAnswersVo.setAnswerList(quizTbQuestionAnswers);
        return questionAnswersVo;
    }
}
